package com.shura.ssm.service.UserService.impl;

import com.shura.ssm.common.entity.User;
import com.shura.ssm.common.utils.MD5Utils;
import com.shura.ssm.mapper.UserMapper;
import com.shura.ssm.service.UserService.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * UserServiceImpl
 * Created by shura
 * Date：2017/9/3
 * Time：16:41
 */
@Service("userService")
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;


    /**
     * 根据id查询用户实体
     *
     * @param userId
     * @return
     * @throws Exception
     */
    @Override
    public User queryById(int userId)throws Exception{
        User user = new User();
        try{
            user = userMapper.queryById(userId);
        }catch(Exception e){
            throw new Exception(e);
        }
        return user;
    }

    /**
     * 新增用户实体
     *
     * @param user
     * @throws Exception
     */
    @Override
    public void newUser(User user) throws Exception {
        if (user == null) {
            return ;
        }

        try {
            user.setPassword(MD5Utils.md5(user.getPassword()));
            userMapper.newUser(user);
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }

    /**
     * 修改用户
     *
     * @param user
     * @throws Exception
     */
    @Override
    public void update(User user) throws Exception {
        if (user == null) {
            return ;
        }

        try {
            userMapper.update(user);
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }

    /**
     * 删除用户
     *
     * @param id
     * @throws Exception
     */
    @Override
    public void deleteById(int id) throws Exception {
        if (id <= 0) {
            return ;
        }
        try {
            userMapper.deleteById(id);
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }

    /**
     * 查询所有用户
     *
     * @return
     * @throws Exception
     */
    @Override
    public List<User> listAll() throws Exception {
        try {
            return userMapper.listAll();
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }

    /**
     * 检查登录状态
     *
     * @param user
     * @return
     * @throws Exception
     */
    @Override
    public boolean checkLogin(User user) throws Exception {
        if (user == null) {
            return false;
        }
        try {
            user.setPassword(MD5Utils.md5(user.getPassword()));
            return userMapper.countByUserNameAndPassword(user.getUserName(), user.getPassword()) > 0 ? true : false;
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }
}
